package session

import (
	"edgex_back_management/dbops"
	"edgex_back_management/model"
	"edgex_back_management/utils"
	"log"
	"reflect"
	"sync"
)

var sessionMap *sync.Map

// 30 MIN
const expiredTime int64 = 30 * 60 * 1000

func init() {
	sessionMap = &sync.Map{}
}

func DeleteSession(sessionId string) {
	sessionMap.Delete(sessionId)
	dbops.DeleteOneSession(sessionId)
}

// 从数据库中加载所有sessions放入缓存map中
func LoadAndCacheSessions() bool {
	sessions, err := dbops.FindAllSession()
	if err != nil {
		log.Printf("Error of LoadAndCacheSessions: %v", err)
		return false
	}

	for _, data := range sessions {
		sessionMap.Store(data.Id, data)
	}
	return true
}

func GenerateNewSession(userName string) string {
	id := utils.GenRandomId()
	ttl := utils.NowInMilli() + expiredTime
	session := &model.Session{Id: id, UserName: userName, TTL: ttl}

	sessionMap.Store(id, session)
	dbops.SaveSession(id, ttl, userName)
	return id
}

// 检查session是否存在, 是否失效
// 失效: return true
// 有效: return false
func IsSessionExpired(sessionId string) (string, bool) {
	session, ok := sessionMap.Load(sessionId)
	if ok {
		if reflect.TypeOf(session).AssignableTo(reflect.TypeOf(model.Session{})) {
			//log.Println("TTL:", session.(model.Session).TTL, "now:", utils.NowInMilli())
			if session.(model.Session).TTL < utils.NowInMilli() {
				DeleteSession(sessionId)
				return session.(model.Session).UserName, true
			} else {
				return session.(model.Session).UserName, false
			}
		} else {
			//log.Println("TTL:", session.(*model.Session).TTL, "now:", utils.NowInMilli())
			if session.(*model.Session).TTL < utils.NowInMilli() {
				DeleteSession(sessionId)
				return session.(*model.Session).UserName, true
			} else {
				return session.(*model.Session).UserName, false
			}
		}

	}

	return "", true
}
